<template>
  <view class="container">
    <view class="form-card">
      <up-form :model="expenseRecord" :borderBottom="true" labelWidth="160rpx" ref="expenseRecordFormRef"
        :rules="expenseRecordRules">
        <!-- 日期 -->
        <up-form-item label="日期" prop="date" required>
          <view class="date-picker-trigger" @tap="datePickerShow = true">
            <text class="date-text">{{ expenseRecord.date || '请选择日期' }}</text>
            <up-icon name="calendar" size="34rpx" color="#888" class="date-icon"></up-icon>
          </view>
          <up-datetime-picker mode="date" :show="datePickerShow" v-model="datePickerValue"
            @confirm="datePickerShow = false" @cancel="datePickerShow = false" @close="datePickerShow = false" />
        </up-form-item>

        <!-- 金额 -->
        <up-form-item label="金额" prop="amount" required>
          <up-input v-model="expenseRecord.amount" clearable type="digit" placeholder="请输入金额" border="bottom" />
        </up-form-item>

        <!-- 类型 -->
        <up-form-item label="类型" prop="type" required>
          <view class="picker-trigger" @tap="showTypePicker = true">
            <text class="picker-text">{{ expenseRecord.type || '请选择类型' }}</text>
            <up-icon name="arrow-down" size="34rpx" color="#888"></up-icon>
          </view>
        </up-form-item>

        <!-- 类型选择器 -->
        <u-picker :show="showTypePicker" :columns="expenseTypes" closeOnClickOverlay @confirm="handleTypeConfirm"
          @cancel="showTypePicker = false" @close="showTypePicker = false" />

        <!-- 里程 -->
        <up-form-item label="里程" prop="mileage">
          <up-input v-model="expenseRecord.mileage" clearable type="digit" placeholder="可选，输入里程数" border="bottom" />
        </up-form-item>

        <!-- 备注 -->
        <up-form-item label="备注" prop="note">
          <up-input v-model="expenseRecord.note" clearable placeholder="可选，添加备注" border="bottom" />
        </up-form-item>
      </up-form>

      <view class="form-footer">
        <up-button @tap="handleCancel" class="cancel-button">取消</up-button>
        <up-button type="primary" @tap="saveRecord" class="confirm-button">确认</up-button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance } from 'vue'
import * as expenseApi from '../../api/expense.js'

// 状态管理
const expenseRecord = ref({
  id: null,
  car_id: null,
  date: '',
  amount: '',
  type: '其他',
  mileage: '',
  note: ''
})
const currentCarId = ref(null)           // 关联的车ID
const datePickerShow = ref(false)        // 日期选择器是否显示
const showTypePicker = ref(false)        // 类型选择器是否显示
const expenseRecordFormRef = ref(null)   // 表单实例引用

// 表单验证规则
const expenseRecordRules = ref({
  date: [{ required: true, message: '请选择日期', trigger: ['change'] }],
  amount: [{ required: true, message: '请输入金额', type: 'number', trigger: ['blur', 'change'] }],
  type: [{ required: true, message: '请选择类型', trigger: ['change'] }],
  mileage: [{ type: 'number', message: '里程必须为数字', trigger: ['blur', 'change'] }]
})

// 费用类型
const expenseTypes = ref([
  [
    '保养', '维修', '保险', '停车', '洗车', '过路', '年检', '其他'
  ]
])

// 日期选择器绑定值（时间戳）
const datePickerValue = computed({
  get: () => {
    return expenseRecord.value.date
      ? new Date(expenseRecord.value.date).getTime()
      : Date.now()
  },
  set: (timestamp) => {
    const d = new Date(timestamp)
    expenseRecord.value.date = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
  }
})

// 处理类型选择确认
const handleTypeConfirm = (e) => {
  expenseRecord.value.type = e.value[0]
  showTypePicker.value = false
}

// 初始化页面数据
const initData = async (recordId) => {
  if (recordId) {
    // 编辑模式：加载现有记录
    try {
      const record = await expenseApi.getExpenseRecordById(recordId)
      expenseRecord.value = record
    } catch (error) {
      console.error('加载记录失败:', error)
      uni.$u.toast('加载记录失败')
    }
  } else {
    // 新增模式：设置默认数据
    const today = new Date()
    const defaultDate = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`

    expenseRecord.value = {
      id: null,
      car_id: currentCarId.value,
      date: defaultDate,
      amount: '',
      type: '保养',
      mileage: '',
      note: ''
    }
  }
}

// 保存记录
const saveRecord = () => {
  // 校验表单
  expenseRecordFormRef.value.validate().then(async valid => {
    if (valid) {
      try {
        const data = {
          ...expenseRecord.value,
          car_id: currentCarId.value,
          amount: Number(expenseRecord.value.amount) || 0.00,
          mileage: Number(expenseRecord.value.mileage) || 0
        }
        let success = false
        console.log('data', data)
        if (expenseRecord.value.id) {
          // 更新记录
          success = await expenseApi.updateExpenseRecord(expenseRecord.value.id, data)
        } else {
          // 添加记录
          success = await expenseApi.addExpenseRecord(data)
        }

        if (success) {
          uni.$u.toast(expenseRecord.value.id ? '更新成功' : '添加成功')
          // 延迟返回，确保用户看到提示
          setTimeout(() => {
            uni.navigateBack()
          }, 1000)
        } else {
          uni.$u.toast(expenseRecord.value.id ? '更新失败' : '添加失败')
        }
      } catch (error) {
        console.error('保存记录失败:', error)
        uni.$u.toast('保存失败，请重试')
      }
    }
  }).catch(() => {
    // 表单验证失败时的处理
  });
}

// 取消操作
const handleCancel = () => {
  uni.navigateBack()
}

// 初始化
onMounted(async () => {
  // 通过getCurrentInstance获取参数
  const instance = getCurrentInstance()
  const attrs = instance?.attrs || {}
  const { carId, recordId } = attrs || {}

  // 确保car_id已设置
  if (!carId) {
    uni.$u.toast('请从列表选择或添加新的车源')
    uni.navigateBack()
    return
  }
  currentCarId.value = carId

  // 设置导航栏标题
  const title = recordId ? '编辑养车记录' : '添加养车记录'
  uni.setNavigationBarTitle({
    title: title
  })

  await initData(recordId)
})
</script>

<style lang="scss" scoped>
/** 容器样式 */
.container {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 20rpx;
}

/** 卡片样式 */
.form-card {
  background-color: #ffffff;
  padding: 20rpx 40rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

/** 日期选择器触发样式 */
.date-picker-trigger {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 0;
  color: #666;
  padding-bottom: 10rpx;
  border-bottom: 1rpx solid #e9ecef;
}

.date-text {
  padding-left: 20rpx;
  color: #333;
  font-size: 28rpx;
}

/** 类型选择器触发样式 */
.picker-trigger {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 0;
  color: #666;
  padding-bottom: 10rpx;
  border-bottom: 1rpx solid #e9ecef;
}

.picker-text {
  padding-left: 20rpx;
  color: #333;
  font-size: 28rpx;
  flex: 1;
}

.date-icon {
  margin-left: auto
}

/** 表单页脚样式 */
.form-footer {
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
}

/** 页脚按钮样式 */
.form-footer up-button {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  font-size: 32rpx;
  border-radius: 16rpx;
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.08);
}

/** 取消按钮样式 */
.cancel-button {
  background-color: #f5f5f5;
  color: #666;
  border: none;
  margin-right: 20rpx;
}

/** 确认按钮样式 */
.confirm-button {
  background-color: #1989fa;
  color: #fff;
  border: none;
}
</style>